<template>
  <ContentWrap>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="130px"
      v-loading="formLoading"
    >
      <div
        class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
      >
        <span>等级信息 </span>
      </div>
      <el-form-item label="代理等级权重" prop="agentLevel">
        <div>
          <div>
            <el-button
              v-for="(level, index) in levelRank"
              :key="index"
              :disabled="level.used"
              :type="formData.agentLevel == level.agentLevel ? 'primary' : ''"
              @click="onSelectLevel(level)"
            >
              {{ level.agentLevel }}</el-button
            >
          </div>
          <Explaintip msg="等级权重越大，等级越高" />
        </div>
      </el-form-item>
      <el-form-item label="代理等级名称" prop="agentLevelName">
        <el-input v-model="formData.agentLevelName" class="w-120!" placeholder="请输入等级名称" />
      </el-form-item>
      <el-form-item label="代理等级背景图" prop="picUrl">
        <UploadImg v-model="formData.picUrl" width="80px" height="80px" />
      </el-form-item>
      <el-form-item label="复购折扣(%)" prop="discountPercent">
        <el-input-number
          v-model="formData.discountPercent"
          :min="0"
          :max="100"
          :precision="0"
          :controls="false"
          class="w-120!"
          placeholder="请输入进货折扣"
        />
      </el-form-item>
      <el-form-item label="成为代理条件" prop="conditions">
        <el-radio-group v-model="formData.conditions">
          <el-radio :value="3">手动审核</el-radio>
          <el-radio :value="0">消费次数</el-radio>
          <el-radio :value="1">消费金额</el-radio>
          <el-radio :value="2">购买指定商品</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="消费次数(次)" prop="sholdPrice" v-if="formData.conditions == 0">
        <el-input-number
          v-model="formData.sholdPrice"
          :min="0"
          :precision="0"
          :controls="false"
          class="!w-120"
          placeholder="请输入消费次数"
        />
      </el-form-item>
      <el-form-item label="消费金额(元)" prop="sholdPrice" v-if="formData.conditions == 1">
        <el-input-number
          v-model="formData.sholdPrice"
          :min="0"
          :precision="2"
          :controls="false"
          class="!w-120"
          placeholder="请输入消费金额(元)"
        />
      </el-form-item>
      <el-form-item label="指定商品金额(元)" prop="sholdPrice" v-if="formData.conditions == 2">
        <div class="flex flex-col">
          <el-input
            v-model="formData.sholdPrice"
            class="w-120!"
            :disabled="priceType == 1"
            @blur="handleChange(formData)"
            :formatter="(value: string) => verifyNumberIntegerAndFloat(value)"
          >
            <template #prepend>
              <el-select
                v-model="priceType"
                class="w-120px!"
                @change="(e) => priceTypeChange(e, formData)"
              >
                <el-option
                  v-for="(item, index) in priceTypeList"
                  :label="item.typeName"
                  :value="item.typeCode"
                  :key="index"
                />
              </el-select>
            </template>
            <template #suffix> 元 </template>
          </el-input>
        </div>
      </el-form-item>
      <el-form-item label="关联商品" prop="sholdSku" v-if="formData.conditions == 2">
        <el-button @click="handleGiveGoods(formData)">选择商品</el-button>
        <SkuList
          class="mt-20px"
          ref="skuListRef"
          :isComponent="false"
          :isDetail="false"
          :hide-stock="true"
          :prop-form-data="spuData"
          @delete="handleChange(formData)"
        >
          <template #extension>
            <el-table-column align="center" label="组合价" min-width="168">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.productConfig.price"
                  :disabled="priceType == 0"
                  @change="handleChange(formData)"
                  :precision="2"
                >
                  <template #suffix> 元 </template>
                </el-input-number>
              </template>
            </el-table-column>

            <el-table-column align="center" label="数量" min-width="168">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.productConfig.skuNumber"
                  @change="handleChange(formData)"
                  :min="1"
                  :precision="0"
                />
              </template>
            </el-table-column>
          </template>
        </SkuList>
      </el-form-item>
      <el-form-item label="是否默认" prop="defaultStatus">
        <el-switch v-model="formData.defaultStatus" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <el-form-item>
      <div class="flex justify-center w-full">
        <el-button :loading="formLoading" type="primary" @click="submitForm"> 保存 </el-button>
        <el-button @click="close">返回</el-button>
      </div>
    </el-form-item>
  </ContentWrap>
  <GiveGoodsSelect ref="giveGoodsSelectRef" :isSelectSku="true" @confirm="selectSku" />
</template>
<script setup lang="ts">
import { useTagsViewStore } from '@/store/modules/tagsView'
import * as ProductSpuApi from '@/api/shop/product/spu'
import SkuList from '@/views/mall/product/components/SkuList.vue'
import GiveGoodsSelect from '@/views/mall/product/components/GiveGoodsSelect.vue'

import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as LevelApi from '@/api/mall/trade/agent/level'
import { CommonStatusEnum } from '@/utils/constants'
import { fenToYuan, floatToFixed2, yuanToFen } from '@/utils'
const { push, currentRoute } = useRouter() // 路由
const { params } = useRoute() // 查询参数
const { delView } = useTagsViewStore() // 视图操作

/** 代理等级表单 **/
defineOptions({ name: 'AgentLevelForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref<LevelApi.LevelVO>({
  agentLevelId: undefined,
  agentLevelName: undefined,
  agentLevel: undefined,
  conditions: 1,
  picUrl: '',

  sholdPrice: undefined,
  discountPercent: undefined,
  // sholdSkuId: 0,
  // recommendReward: { 1: 1, 2: 2 },
  status: CommonStatusEnum.ENABLE
})
const formRules = reactive({
  agentLevelName: [{ required: true, message: '等级名称不能为空', trigger: 'blur' }],
  agentLevel: [{ required: true, message: '等级权重不能为空', trigger: 'blur' }],
  // discountPercent: [{ required: true, message: '享受折扣不能为空', trigger: 'blur' }],
  sholdPrice: [{ required: true, message: '金额不能为为空', trigger: 'change' }]
})
interface levelRankVO {
  agentLevel: number
  used: boolean
}
const levelRank = ref<levelRankVO[]>([])
const formRef = ref() // 表单 Ref

// 购买指定商品 逻辑
import { verifyNumberIntegerAndFloat } from '@/utils/formatter'
import { cloneDeep } from 'lodash-es'
import { isEmpty } from '@/utils/is'

const priceType = ref(0)
const priceTypeList = ref<any>([
  {
    typeName: '一口价',
    typeCode: 0
  },
  {
    typeName: '累加价',
    typeCode: 1
  }
])
// ================= 商品选择相关 =================
export interface DiscountProductVO {
  skuId: number
  price?: number
  skuNumber: number
}
const giveGoodsSelectRef = ref() // 商品和属性选择 Ref
const skuListRef = ref() // sku   配置组件Ref

const selectSku = (skuIds: number[]) => {
  getSkuDetails(skuIds, undefined, nowItem.value)
}

/** 获取SKU详情 */
const spuData = ref<any>({
  skus: []
}) //为了统一组件格式
const getSkuDetails = async (
  skuIds: number[] | undefined,
  products?: DiscountProductVO[],
  nowItem?: any
) => {
  const data = await ProductSpuApi.getSkuPageList2({ skuIds } as any)
  if (data.list.length == 0) {
    return
  }
  console.log(nowItem)
  data.list.forEach((sku) => {
    let config: DiscountProductVO = {
      skuId: sku.skuId!,
      price: undefined,
      skuNumber: 0
    }

    const existData = spuData.value.skus.find((ele: any) => {
      return ele.skuId == sku.skuId
    })
    if (existData) {
      config = existData.productConfig
    }

    if (typeof products !== 'undefined') {
      const product = products.find((item) => item.skuId === sku.skuId)
      if (product) {
        product.price = fenToYuan(product.price!) as any
      }
      config = product || config
    }
    sku.productConfig = config
    sku.price = floatToFixed2(sku.price)
  })
  if (nowItem) {
    spuData.value = {
      skus: []
    }
    data.list.forEach((ele) => {
      ele.salesPrice = ele.price
    })

    spuData.value.skus = data.list
    setTimeout(() => {
      calculateItemDiscountPrice(nowItem)
    }, 100)
  }
}

const calculatePrice = (nowItem) => {
  let price = 0
  spuData.value.skus.forEach((ele) => {
    price += Number(yuanToFen(ele.productConfig.price)) * Number(ele.productConfig.skuNumber)
  })
  nowItem.sholdPrice = fenToYuan(price)
}
//计算 参与组合商品总零售价
const calculateTotalPrice = () => {
  return new Promise<any>((resolve) => {
    let totalPrice = 0 //单个商品总活动一口价
    spuData.value.skus.forEach((ele) => {
      totalPrice += Number(yuanToFen(ele.price)) * Number(ele.productConfig.skuNumber)
    })
    resolve(totalPrice)
  })
}
//计算一口价下每个商品的活动价格
const calculateItemDiscountPrice = (nowItem) => {
  let price = priceType.value == 0 ? Number(yuanToFen(nowItem.sholdPrice)) : 0 //活动一口价

  calculateTotalPrice().then((totalPrice) => {
    spuData.value.skus.forEach((ele) => {
      let rate = Number(yuanToFen(ele.price)) / totalPrice

      ele.productConfig.price = Number(fenToYuan(price * rate))
    })
  })
}
/**
 *
 *  价格或数量变化
 * @param nowItem
 */
const handleChange = (nowItem) => {
  if (priceType.value == 0) {
    calculateItemDiscountPrice(nowItem)
  } else {
    calculatePrice(nowItem)
  }
}
const priceTypeChange = (e, nowItem) => {
  if (e == 0) {
    calculateItemDiscountPrice(nowItem)
  } else {
    calculatePrice(nowItem)
  }
}
const nowItem = ref() //当前选中的数据
const handleGiveGoods = (item: any) => {
  nowItem.value = item
  const selectedSkuIds = spuData.value.skus.map((ele) => {
    return ele.skuId
  })
  giveGoodsSelectRef.value.open(selectedSkuIds)
}

/** 打开弹窗 */
const getDetail = async () => {
  const id = params.id as unknown as number
  levelRank.value = await LevelApi.getUsedLevel()
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await LevelApi.getLevel(id)
      if (formData.value.conditions != 0) {
        formData.value.sholdPrice = Number(fenToYuan(formData.value.sholdPrice || 0))
      }
      if (!isEmpty(formData.value.sholdSku)) {
        await getSkuDetails(
          formData.value.sholdSku?.map((sku) => sku.skuId),
          formData.value.sholdSku,
          formData.value
        )
      }
    } finally {
      formLoading.value = false
    }
  }
}
/**
 * 获取所有 sku 活动配置
 *
 * @param extendedAttribute 在 sku 上扩展的属性，例：秒杀活动 sku 扩展属性 productConfig 请参考 seckillActivity.ts
 */
const getSkuConfigs = (extendedAttribute: string) => {
  skuListRef.value.validateSku()
  const products: any[] = []
  spuData.value.skus?.forEach((sku: any) => {
    products.push(sku[extendedAttribute] as any)
  })
  return products
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  if (formData.value.conditions == 2) {
    const products = cloneDeep(getSkuConfigs('productConfig'))
    products.forEach((item: DiscountProductVO) => {
      item.price = yuanToFen(item.price!)
    })
    formData.value.sholdSku = products
  }
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = cloneDeep(unref(formData.value)) as unknown as LevelApi.LevelVO

    if (data.conditions != 0) {
      data.sholdPrice = yuanToFen(data.sholdPrice || 0)
    }
    if (data.conditions == 2) {
      data.priceType = priceType.value
    }
    const id = params.id as unknown as number

    if (!id) {
      await LevelApi.createLevel(data)
      message.success(t('common.createSuccess'))
    } else {
      await LevelApi.updateLevel(data)
      message.success(t('common.updateSuccess'))
    }
    // 发送操作成功的事件
    close()
  } finally {
    formLoading.value = false
  }
}

/**
 * 选择等级权重
 */
const onSelectLevel = (level) => {
  formData.value.agentLevel = level.agentLevel
}
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    agentLevelId: undefined,
    agentLevelName: undefined,
    agentLevel: undefined,
    conditions: 1,
    sholdPrice: undefined,
    discountPercent: undefined,
    picUrl: '',

    // sholdSkuId: 0,
    // recommendReward: { 1: 1, 2: 2 },
    status: CommonStatusEnum.ENABLE
  }
  formRef.value?.resetFields()
}
/** 关闭按钮 */
const close = () => {
  delView(unref(currentRoute))
  push({ name: 'AgentLevel' })
}
/** 初始化 */
onMounted(async () => {
  await getDetail()
})
</script>
<style lang="scss" scoped>
:deep(.el-input__inner) {
  text-align: center;
}
</style>
